package Network.homework;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket clientSocket=null;
    public TcpEchoClient(String serverIP,int serverPort) throws IOException {
        clientSocket=new Socket(serverIP,serverPort);
    }
    public void start(){
        System.out.println("客户端启动");
        try(Scanner scanConsole=new Scanner(System.in);
            InputStream inputStream=clientSocket.getInputStream();
            Scanner scanNetwork=new Scanner(inputStream);
            OutputStream outputStream=clientSocket.getOutputStream();
            PrintWriter printWriter=new PrintWriter(outputStream)){
            while(true){
                System.out.print("->");
                //1.从控制台输入请求
                if(!scanConsole.hasNext()){
                    break;//请求输入结束
                }
                //获取请求
                String request=scanConsole.next();
                //2.发送请求 通过PrintWriter.println发送请求
                printWriter.println(request);
                printWriter.flush();//刷新缓冲区
                //3.获取响应
                //通过Scanner 读取返回大响应
                String response=scanNetwork.next();
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            try {
                clientSocket.close();//关闭Socket 释放 文件描述符表
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1", 9090);
        tcpEchoClient.start();
    }

}
